<template>
  <div>
    <el-card shadow="hover">
      <el-row :gutter="20" class="selectBox" type="flex" align="middle">
        <el-col :span="3" class="label"><span @click="openRH">选择网格员:</span></el-col>
        <el-col :span="4">
          <el-select v-model="grid" placeholder="选择网格员" @change="selectGrid">
            <el-option
              v-for="item in gridLine"
              :key="item.grid"
              :label="item.name"
              :value="item.grid"
              :disabled="!item.tDeviceId || !item.line.length"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="10">
          <el-button type="primary" plain @click="trajectory = !trajectory"
            >{{ trajectory ? '隐藏' : '显示' }}所有轨迹</el-button
          >
          <el-button type="primary" plain @click="reload = !reload">{{ reload ? '关闭' : '开启' }}自动刷新</el-button>
          <Video ref="video" />
        </el-col>
      </el-row>
      <baidu-map
        class="bm-view"
        :center="ahora"
        :zoom="15"
        :scroll-wheel-zoom="true"
        map-type="BMAP_HYBRID_MAP"
        ak="VMI7fuQnbCg9TwvIO2joHBTaYTG12s9e"
      >
        <bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']" anchor="BMAP_ANCHOR_TOP_LEFT"></bm-map-type>
        <div v-for="item in gridLine" :key="item.grid">
          <!-- 路径 -->
          <div v-for="(lineItem, index) in item.line" :key="index">
            <bm-polyline
              v-if="item.show || (lineItem.length && trajectory)"
              :path="lineItem"
              :stroke-color="item.color"
              :stroke-opacity="1"
              :stroke-weight="5"
            >
            </bm-polyline>
          </div>

          <!-- 弹窗 -->
          <bm-overlay
            v-if="item.line.length"
            v-show="item.show"
            pane="labelPane"
            class="sample"
            @draw="
              ({ el, BMap, map }) => {
                draw({ el, BMap, map }, item.line[item.line.length - 1])
              }
            "
          >
            <i class="el-icon-close close" @click="close(item)"></i>
            <div class="contBox">
              <img :src="item.avatar" class="icon" alt="" />
              <div>
                <p>姓名：{{ item.name }}</p>
                <p>区域：{{ item.gridName }}</p>
                <p>手机：{{ item.phone }}</p>
              </div>
            </div>
            <div v-if="item.cameraIndexCode" class="contBox right">
              <i class="el-icon-microphone buttom" @click="doCall(item.number, false)"></i>
              <i class="el-icon-video-camera buttom" @click="doCall(item.number, true)"></i>
              <i v-if="roleId != 3" class="el-icon-view buttom" @click="openHK(item.cameraIndexCode)"></i>
            </div>
          </bm-overlay>

          <!-- 标点 -->
          <bm-marker
            v-if="item.line.length && item.tDeviceId"
            :position="item.line[item.line.length - 1][item.line[item.line.length - 1].length - 1]"
            @click="showWin(item)"
            :icon="{ url: require('@/assets/map-ren.png'), size: { width: 35, height: 60 } }"
          >
            <bm-label :content="item.name" :label-style="labelStyle" :offset="{ width: -10, height: -23 }"></bm-label>
          </bm-marker>
        </div>
      </baidu-map>
    </el-card>
  </div>
</template>

<script>
import * as api from '@/api/project'
import BaiduMap from 'vue-baidu-map/components/map/Map.vue'
import BmPolyline from 'vue-baidu-map/components/overlays/Polyline'
import BmMarker from 'vue-baidu-map/components/overlays/Marker'
import BmOverlay from 'vue-baidu-map/components/overlays/Overlay'
import BmLabel from 'vue-baidu-map/components/overlays/Label'
import BmMapType from 'vue-baidu-map/components/controls/MapType'
import Video from '@/components/video'

export default {
  data() {
    return {
      gridLine: [],
      ahora: { lng: 113.9009812868343, lat: 23.152397272862775 },
      ahoraState: false,
      time: null,
      trajectory: false,
      reload: true,
      color: [],
      grid: null,
      roleId: null,
      labelStyle: { 'border-color': 'black', 'border-radius': '4px' },
    }
  },
  components: {
    BaiduMap,
    BmPolyline,
    BmMarker,
    BmOverlay,
    BmLabel,
    BmMapType,
    Video,
  },
  created() {
    this.getGrid()
  },
  mounted() {
    this.time = setInterval(() => {
      if (this.reload) {
        this.getGrid(true)
      }
    }, 10000)
    this.roleId = localStorage.getItem('roleId')
  },
  methods: {
    // 获取人员
    getGrid(e) {
      let data = {
        gridFlag: 1,
        pageNo: 1,
        pageSize: 1000,
      }
      api.userList(data).then(res => {
        if (res.code == '200') {
          for (let i = 0, arr = res.data.records; i < arr.length; i++) {
            let item = arr[i]
            if (item.tDeviceId) {
              if (e) {
                this.refLineData()
              } else {
                this.getLineData(item, i)
              }
            }
            this.color.push(this.getCasualeColor())
          }
        }
      })
    },
    // 获取随机颜色
    getCasualeColor() {
      let random = Math.random()
      if (random < 0.07) {
        random = Math.random()
      }
      let num = Math.floor(random * 16777215).toString(16)
      if (num.length < 6) {
        num += '1'
      }
      return '#' + num
    },
    // 渲染地图数据
    async getLineData(item, index) {
      this.gridLine = []
      let data = {
        status: '',
        userId: item.userId,
      }
      let gridData = {
        grid: item.userId,
        name: item.fullName,
        show: false,
        avatar: item.avatar,
        gridName: item.gridName,
        color: this.color[index],
        phone: item.phone,
        cameraIndexCode: item.cameraIndexCode ?? '',
        line: [],
        number: item.haikangNumber,
        tDeviceId: item.tDeviceId,
      }
      gridData.line = await this.getLocation(data)
      this.gridLine.push(gridData)
    },
    async refLineData() {
      for (let i = 0, line = this.gridLine; i < line.length; i++) {
        const item = line[i]
        let data = {
          status: '',
          userId: item.grid,
        }
        item.line = await this.getLocation(data)
      }
    },
    getLocation(data) {
      return api.locationGet(data).then(res => {
        if (res.code == '200') {
          let hours = new Date().getHours()
          let sxw = hours >= 12 ? 1 : 0
          let rowArr = res.data[sxw]
          let arr = [],
            add = []
          for (let i = 0; i < rowArr.length; i++) {
            if (rowArr[i] == 'HS') {
              rowArr.splice(0, i)
              if (add.length) arr.push(add)
              i = 0
              add = []
            } else {
              const itemArr = rowArr[i].split(',')
              let obj = {}
              for (let i = 0; i < itemArr.length; i++) {
                let iArr = itemArr[i].split(':')
                obj[iArr[0]] = Number(iArr[1])
              }
              if (!this.ahoraState && i == rowArr.length - 1) {
                this.ahora.lat = obj.lat
                this.ahora.lng = obj.lng
                this.ahoraState = true
              }
              add.push(obj)
              if (i == rowArr.length - 1) {
                arr.push(add)
              }
            }
          }
          return arr
        }
      })
    },
    draw({ el, BMap, map }, line) {
      const pixel = map.pointToOverlayPixel(new BMap.Point(line[line.length - 1].lng, line[line.length - 1].lat))
      el.style.left = pixel.x - 100 + 'px'
      el.style.top = pixel.y - 150 + 'px'
    },
    showWin(item) {
      item.show = !item.show
      this.ahora.lat = item.line[item.line.length - 1][item.line[item.line.length - 1].length - 1].lat
      this.ahora.lng = item.line[item.line.length - 1][item.line[item.line.length - 1].length - 1].lng
    },
    openHK(code) {
      if (!code) {
        this.$message.error('网格员未登录设备!')
        return
      }
      window.open(
        'http://sw.hczwfu.cn/hk/index.html?code=' + code,
        'pop',
        'status=0, titlebar=0, toolbar=0, location=0, resizable=0, height=400, width=800, scrollbars=0 ,left=380,top=200'
      )
    },
    openRH() {
      window.open(
        'https://36.140.66.86:1443/iportal/',
        'pop',
        'status=0, titlebar=0, toolbar=0, location=0, resizable=0, height=850, width=1300, scrollbars=0 ,left=380,top=200,noopener=yes,noreferrer=yes'
      )
    },
    selectGrid(e) {
      let gridInfo = this.gridLine.find(item => item.grid === e)
      this.showWin(gridInfo)
    },
    close(item) {
      item.show = false
      this.grid = null
    },
    openChat() {
      this.$refs.video.communication.displayChatPanel(true)
    },
    doCall(num, e) {
      this.$refs.video.communication.doCall({
        isGroup: true,
        number: num,
        resId: 'd1',
        useVideo: e,
      })
    },
  },
  beforeDestroy() {
    clearInterval(this.time)
  },
}
</script>

<style lang="scss" scoped>
.bm-view {
  width: 100%;
  height: 800px;
}
.refresh {
  width: 100px;
  height: 30px;
  line-height: 30px;
  background-color: #fff;
  border: solid 1px #999;
  border-radius: 4px;
  cursor: pointer;
}
.sample {
  width: 220px;
  height: 70px;
  line-height: 40px;
  overflow: hidden;
  box-shadow: 0 0 5px #000;
  color: #fff;
  text-align: center;
  padding: 10px;
  position: absolute;
  background: rgba(0, 0, 0, 0.75);
  .contBox {
    display: flex;
    align-items: center;
    text-align: left;
    .icon {
      width: 50px;
      height: 50px;
      margin-right: 10px;
    }
    p {
      line-height: 16px;
      margin: 0;
      font-size: 14px;
    }
    &.right {
      justify-content: right;
    }
    .buttom {
      padding: 5px 5px 0 0;
      cursor: pointer;
      font-size: 18px;
      &:hover {
        color: rgb(255, 47, 47);
      }
    }
  }
  .close {
    position: absolute;
    right: 10px;
    top: 5px;
    width: 10px;
    height: 10px;
    cursor: pointer;
    &:hover {
      color: rgb(255, 47, 47);
    }
  }
}
.selectBox {
  padding-bottom: 20px;
  .label {
    text-align: right;
  }
}
</style>
